$(function() {
	var i = 0;
	doPost()
	function doPost(){
	fetch('./list.do?type=json&page='+i+'',{credentials: 'same-origin'})
	.then(function(response) {
		return response.json();
	}).then(
			function(articles) {
				
				var $ul = $('#list-articles');
				articles.forEach(function(art) {
					$ul.append('<li class="list-group-item">' + '<h3>'
							+ art.title + '</h3>' + '<p>' + art.content
							+ '</p>' + '<p>' + art.publishDate
							+ '</p>'
							+ '<button data-id="' + art.id + '">删除</button>' +'</li>');
				})
			})
			.then(function() {
				$('#list-articles li button').on('click', function() {
					var $self = $(this)
					fetch('./del.do?ajax=true&id=' + $self.data('id'), {credentials: 'same-origin'})
						.then(function(res) {
							return res.json()
						})
						.then(function(obj) {
							if(obj.ok === 1) {
								$self.parent('li').remove()
							}
						})
						.catch(function(err) {
							alert(err)
						})
				})
			})
	}
	

	
	$(window).scroll(function() {
		
		var scrollTop = $(this).scrollTop();
		var scrollHeight = $(document).height();
		var windowHeight = $(this).height();
//		alert(scrollTop +"** "+scrollHeight + "** " + windowHeight);
		if (scrollTop + windowHeight >= scrollHeight-500) {
			i++;
			
			doPost();
		}
	});
})
